/**
 * Created by HMH on 2017/7/15.
 */
import Cookies from 'js-cookie';
import * as userApi from '../../api/user.js'

const user = {
  state: {
    token: Cookies.get('token'),
    userInfo: {username: null, password: null}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER: (state, data) => {
      // console.log(" ⛅ ", data);
      state.userInfo = data;
    }
  },
  
  actions: {
    login({commit}, data) {
      return new Promise((resolve, reject) => {
        
        console.log(" ⛅ send login data");
        userApi.login(data).then((data) => {
          //deal data
          console.log(' ⛅ get response');
          commit('SET_USER', data.user);
          commit('SET_TOKEN', data.token);
          Cookies.set('token', data.token);
          resolve(data);
        }).catch((err) => {
          console.log(" 🌧 error curred :", err);
          reject(err);
        });
      });
      
    },
    getUserInfoByToken({commit}, data) {
      return new Promise((resolve, reject) => {
        
        console.log("send login data");
        userApi.getInfoByToken(data).then((data) => {
          //deal data
          commit('SET_USER', data);
          resolve(data);
        }).catch((err) => {
          
          console.log(" 🌧 error curred :", err);
          reject(err);
        });
      });
    },
    
    logout({commit}) {
      return new Promise((resolve, reject) => {
        console.log("logout");
        commit('SET_TOKEN', null);
        Cookies.set('token', null);
        commit('SET_USER', {username: null, password: null});
        resolve();
      });
    }
  }
};


export default user;
